package org.sao.security.app.config;

import org.sao.security.core.authentication.mobile.SmsCodeAuthenticationSecurityConfig;
import org.sao.security.core.properties.SecurityConstants;
import org.sao.security.core.properties.SecurityProperties;
import org.sao.security.core.validate.code.ValidateCodeSecurityConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.social.security.SpringSocialConfigurer;


@EnableResourceServer
@Configuration
public class ResourcesServerConfig  extends ResourceServerConfigurerAdapter  {


	@Autowired
	private SecurityProperties securityProperties;
	
	@Autowired
	private ValidateCodeSecurityConfig validateCodeSecurityConfig;
	
	@Autowired
	private SpringSocialConfigurer zySocialSecurityConfig;
	
	@Autowired
	private SmsCodeAuthenticationSecurityConfig smsCodeAuthenticationSecurityConfig;
	
	@Autowired
	AuthenticationFailureHandler zyAuthenticationFailureHandler;
	
	@Autowired
	AuthenticationSuccessHandler zyAuthenticationSuccessHandler;
	
	@Override
	public void configure(HttpSecurity http) throws Exception {
		// TODO Auto-generated method stub
		http.formLogin()
		.loginPage(SecurityConstants.DEFAULT_UNAUTHENTICATION_URL)
		.loginProcessingUrl(SecurityConstants.DEFAULT_LOGIN_PROCESSING_URL_FORM)
		.successHandler(zyAuthenticationSuccessHandler)
		.failureHandler(zyAuthenticationFailureHandler);
		
		http
			.apply(validateCodeSecurityConfig)
		    .and()
			.apply(smsCodeAuthenticationSecurityConfig)
			.and()
			.apply(zySocialSecurityConfig)
			.and()
			    .authorizeRequests()
			    .antMatchers(SecurityConstants.DEFAULT_UNAUTHENTICATION_URL).permitAll()
			    .antMatchers(SecurityConstants.DEFAULT_LOGIN_PROCESSING_URL_MOBILE).permitAll()
			    .antMatchers(SecurityConstants.DEFAULT_VALIDATE_CODE_URL_PREFIX+"/*").permitAll()
			    .antMatchers(securityProperties.getBrowser().getLoginPage()).permitAll()
			    .antMatchers(securityProperties.getBrowser().getSession().getSessionInvalidUrl()+".json").permitAll()
			    .antMatchers(securityProperties.getBrowser().getSession().getSessionInvalidUrl()+".html").permitAll()
			    .anyRequest()
			    .authenticated()
			    .and()
			    .csrf().disable();
	}

	
}
